import requests
from json import loads
# 注：账号密码未给出，运行程序会报错，请完善账号密码
class Login12306(object):
    def __init__(self):
        self.session = requests.Session()
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0'
        }
        self.session.headers.update(header)
    def index(self):
        # 访问登录首页,为了获取验证码和其他请求
        login_url = 'https://kyfw.12306.cn/otn/login/init'
        self.session.get(login_url)
        # 获取验证码保存
        captcha_url = 'https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.2803567094214129'
        captcha_reponse = self.session.get(captcha_url)
        with open('captcha.jpg', 'wb') as f:
            f.write(captcha_reponse.content)


    # 校验验证码的方法函数
    def check_way(self,index):
        map = {
            '1': '37,42',
            '2': '111,42',
            '3': '180,42',
            '4': '254,42',
            '5': '37,118',
            '6': '111,118',
            '7': '180,118',
            '8': '254,118',
        }
        # 根据输入的序号来获取相应的坐标
        indexs = index.split(',')
        temp = []
        for index in indexs:
            temp.append(map[index])
        reponse = ','.join(temp)
        return reponse

    # 校验验证码
    def check_captcha(self):
        self.index()
        # 获取验证码坐标
        captcha_coordinate = self.check_way(input('请输入正确验证码序号: '))
        check_captcha_url = 'https://kyfw.12306.cn/passport/captcha/captcha-check'
        form_data = {
            'answer':captcha_coordinate,
            'login_site':'E',
            'rand':'sjrand'
        }
        check_reponse = self.session.post(check_captcha_url, data=form_data)
        # print(check_reponse.json())
        if check_reponse.json()['result_code'] == '4':
            # print('验证码校验成功')
            return True
        else:
            # print('验证码校验失败')
            return False

    # 校验用户名密码
    def check_user(self):
        if self.check_captcha():
            user_login_url = 'https://kyfw.12306.cn/passport/web/login'
            form_data = {
                'username':'****',
                'password':'****',
                'appid':'otn'
            }
            login_reponse = self.session.post(user_login_url,data=form_data)
            if login_reponse.json()['result_code'] == 0:
                # print('账户校验成功')
                return True
            else:
                # print('账户校验失败')
                return False
        else:
            self.check_captcha()
    def check_token(self):
        if self.check_user():
            # 获取权限token
            auth_url = 'https://kyfw.12306.cn/passport/web/auth/uamtk'
            auth_reponse = self.session.post(auth_url,data={'appid':'otn'})
            #此时获取到token权限  {"result_message":"验证通过","result_code":0,"apptk":null,"newapptk":"wKX0g1A1rc0I3JXtuK1Pec3dQKk0oTl6q_42lvXOl3kij1210"}
            #6.提取权限值，发送post请求，登录成功
            if auth_reponse.json()['result_code'] == 0:
                check_token_url = 'https://kyfw.12306.cn/otn/uamauthclient'
                check_token_url_reponse = self.session.post(check_token_url,data={'tk':auth_reponse.json()['newapptk']})
                # 此时用户验证成功，携带session和验证通过的token进行再次登录
                check_login_url = 'https://kyfw.12306.cn/otn/login/userLogin'
                res = self.session.post(check_login_url, data={'_json_att': ''})
                # print(res.text)
                # print(self.session.cookies)
        else:
            self.check_user()
    # 查询列车信息
    def login_success(self):
        self.check_token()
        car_url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2018-11-11&leftTicketDTO.from_station=BJP&leftTicketDTO.to_station=HZH&purpose_codes=ADULT'

        car_url_reponse = self.session.get(car_url)
        dic = loads(car_url_reponse.text)
        for result in dic['data']['result']:
            c = str(result).split('|')
            print("车次:%s;出发地:%s;到达地:%s;出发时间:%s;到达时间:%s,状态%s;历程:%s;商务特等座:%s;一等座:%s;"
                  "二等座:%s;高级软卧:%s;软卧:%s;动卧:%s;硬卧:%s;软座:%s;硬座:%s;无座:%s;其他:%s;备注:%s"
                  % (
                      c[3], c[6], c[7], c[8], c[9], c[11], c[10], "--", c[20], c[21], c[22], c[23], c[24], c[25], c[26],
                      c[27], c[28], c[29], c[1]))
login = Login12306()
login.login_success()



